<template>
  <page-header-wrapper>
    <a-card :bordered="false" class="card_top_padding" style="margin-bottom: 11px">
       <a-tabs  @change="changeTab" activeKey="2">
        <a-tab-pane key="1" tab="优惠券管理" ></a-tab-pane>
        <!-- <a-tab-pane key="2" tab="自动发放"></a-tab-pane> -->
    </a-tabs>
      <div class="table-page-search-wrapper" v-if="true">
        <a-form layout="inline">
          <a-row :gutter="20">
            <a-col :md="4" :sm="24">
              <a-form-item style="margin: 0">
                <a-input placeholder="请输入优惠券名称" v-model="queryParam.search_key" >
                    <a-icon slot="suffix" type="search" />
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons" style="margin: 0">
                <a-button style="margin-right: 8px" @click="resetQueryParams">重置</a-button>
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" class="card_style_re">
      <div class="table-operator" style="float: right">
        <a-button type="primary" @click="onAdd" icon="plus">新建</a-button>
      </div>
      <a-divider />

      <s-table rowKey="id" size="default" :columns="columns" :data="loadData" ref="table">
        <span slot="send_times" slot-scope="send_times">
          <span v-if="send_times < 1">无限制</span>
          <span v-else>{{ send_times }}</span>
        </span>
        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-popconfirm title="确认删除该发放吗？" @confirm="handleDelete(record)">
            <a-button type="link" size="small">删除</a-button>
          </a-popconfirm>
        </span>
      </s-table>
      <a-modal
        :title="isNew ? '创建发放' : '编辑发放'"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        :bodyStyle="{ height: '600px', overflow: 'auto' }"
        v-model="visible"
        @ok="handleOk"
      >
        <a-form class="permission-form" :form="form">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" style="display: none" label="主键" hasFeedback>
            <a-input placeholder="主键" :disabled="!isNew" v-decorator="['id']" />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="触发事件" extra="">
            <a-radio-group v-decorator="['event', { initialValue: 2 }]">
              <a-radio :value="1"> 页面转发 </a-radio>
              <a-radio :value="2"> 购买并付款 </a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="优惠券">
            <a-select
              v-decorator="['coupon_id', { rules: [{ required: true, message: '请选择优惠券' }] }]"
              placeholder="请选择优惠券"
            >
              <a-select-option v-for="(item, index) in type_list" :key="index" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="最多发放次数"
            :extra="'如不限制发放次数，请填写0'"
          >
            <a-input-number placeholder="最多发放次数" :min="0" v-decorator="['send_times', { initialValue: 0 }]" />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import pick from 'lodash.pick'
import { STable } from '@/components'
import { couponAutoSendList, couponAutoSendDel, couponAutoSendAdd, couponAutoSendEdit } from '@/api/marketing'

const STATUS = {
  1: '显示',
  0: '不显示',
}

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '触发事件',
    dataIndex: 'event_text',
  },
  {
    title: '优惠券',
    dataIndex: 'coupon_name',
  },
  {
    title: '发放次数限制',
    dataIndex: 'send_times',
    scopedSlots: {
      customRender: 'send_times',
    },
  },
  {
    title: '添加时间',
    dataIndex: 'created_at',
  },
  {
    title: '操作',
    width: '150px',
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action',
    },
  },
]

export default {
  name: 'ArticleList',
  components: {
    STable,
  },
  data() {
    return {
      isNew: false,
      visible: false,
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 5,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 16,
        },
      },
      form: this.$form.createForm(this),
      // 表头
      columns,
      modalLoading: false,
      statusSelectValue: {
        key: '1',
        label: '显示',
      },
      type_list: [],
      form_pic_url: '',
      // 查询条件参数
      queryParam: {
        search_key: null,
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        Object.assign(parameter, this.queryParam)
        return couponAutoSendList(parameter)
          .then((res) => {
            console.log('couponAutoSendList', res)
            this.type_list = res.data.type_list
            return res.data
          })
          .catch((err) => {
            this.$message.error(err.message)
            this.$refs.table.localLoading = false
          })
      },
    }
  },
  filters: {
    statusFilter(key) {
      return STATUS[key]
    },
  },
  created() {},
  activated(){
    this.$refs.table.refresh()
  },
  methods: {
    changeTab(val) {
      if (val == 1) {
        this.$router.push({ name: 'CouponList' })
      }
    },
    changeShow(item) {
      console.log(item)
      const hide = this.$message.loading('请求中...', 0)
      couponAutoSendEdit({
        key: item.id,
        is_show: item.is_show,
      })
        .then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success('操作成功！')
            this.$refs.table.refresh()
          } else {
            this.$error({
              content: res.msg,
            })
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
          this.modalLoading = false
        })
    },
    handleEdit(record) {
      this.isNew = false
      this.visible = true
      record.event = parseInt(record.event)
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(record, ['id', 'event', 'send_times', 'coupon_id']))
      })
    },
    handleOk(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (err) {
          return false
        }
        this.modalLoading = true
        if (this.isNew) {
          couponAutoSendAdd(values)
            .then((res) => {
              console.log(res)
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg,
                })
              } else {
                this.$message.success('发放创建成功！')
                this.visible = false
                this.$refs.table.refresh()
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        } else {
          couponAutoSendEdit(values)
            .then((res) => {
              console.log(res)
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg,
                })
              } else {
                this.$message.success('发放编辑成功！')
                this.visible = false
                this.$refs.table.refresh()
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        }
      })
    },
    onAdd: function () {
      this.isNew = true
      this.visible = true
      this.form_pic_url = ''
    },
    handleDelete: function (record) {
      const hide = this.$message.loading('删除中...', 0)
      couponAutoSendDel({
        key: record.id,
      })
        .then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success('发放删除成功！')
            this.$refs.table.refresh()
          } else {
            this.$error({
              content: res.msg,
            })
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
          this.modalLoading = false
        })
    },
    resetQueryParams() {
      Object.assign(this.queryParam, {
        search_key: null,
      })
      this.$refs.table.refresh(true)
    },
  },
}
</script>

<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
</style>
